/**
 * Urban Parks
 *
 * Team M&M's:
 * Michael Satran Jr
 * Michael Pogson
 * Stephen Hunter
 *
 * Date: Feb 17, 2012
 */
package view;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import model.Job;
import model.User;

import controller.Controller;

/**
 * A super panel of all the UserPanels.
 * 
 * @author Michael Satran Jr
 */
public abstract class UserPanel {
	
	/**
	 * Frame which will contain the UserPanel.
	 */
	private JFrame my_frame;
	
	/**
	 * Starts the panel in the given frame
	 * @param the_frame The given frame.
	 * @param the_panel The given panel.
	 */
	public void start(JFrame the_frame, JPanel the_panel) {
		my_frame = the_frame;
		my_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    my_frame.setLocationRelativeTo(null);
	    
	    my_frame.setBounds(100, 100, 450, 300);
	    my_frame.setContentPane(the_panel);
	    my_frame.pack();
	    my_frame.setVisible(true);
	}
	
	/**
	 * Starts the panel in the given frame
	 * @param the_frame The given frame.
	 * @param the_panel The given panel.
	 * @param the_controller A reference to the controller.
	 */
	public void start(JFrame the_frame, JPanel the_panel, final Controller the_controller) {
	    the_frame.addWindowListener(new WindowAdapter() {
		   	public void windowClosing(WindowEvent e) {
		  		List<String[]> job_lines = Main.reParseJobs((List<Job>) the_controller.getAllJobs());
		   		Main.writeToFile(new File("jobs.txt"), job_lines);
		   		
		   		List<String[]> user_lines = Main.reParseUsers(the_controller.getUsers());
		   		Main.writeToFile(new File("users.txt"), user_lines);
		   	}
		   	public void windowClosed(WindowEvent e) {
		   		windowClosing(e);
		   		GUI mainGUI = new GUI(the_controller);
				mainGUI.start();
		   	}
	    });
	    start(the_frame, the_panel);
	}
	
	/**
	 * Starts the Panel.
	 */
	public abstract void start();
	
	/**
	 * Sets up the panel by adding buttons etc.
	 */
	public abstract void setup();
	
	/**
	 * Sets up a given JTable and jobs.
	 * @param the_table The table to add jobs to
	 * @param the_jobs The jobs to add to the provided table.
	 */
	public void setupTable(JTable the_table, List<Job> the_jobs, Object[] the_columns) {
		Object[][] table_data = new Object[the_jobs.size()][1];
		
		int i = 0;
		for (Job offset : the_jobs) {
			table_data[i][0] = offset;
			i++;
		}
		DefaultTableModel model = new DefaultTableModel(table_data, the_columns);
		the_table.setModel(model);
	}

}
